﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FakeXiecheng.API.Helper
{
    public class PaginationList<T> : List<T>
    {
        //    public int CurrentPage { get; set; }
        //    public int PageSize { get; set; }

        //    public PaginationList(int currentPage, int pageSize, List<T> items)
        //    {
        //        CurrentPage = currentPage;
        //        PageSize = pageSize;
        //        AddRange(items);
        //    }

        //    public static async Task<PaginationList<T>> CreateAsync(
        //        int currentPage, int pageSize, IQueryable<T> result)
        //    {
        //        // pagination
        //        // skip
        //        var skip = (currentPage - 1) * pageSize;
        //        result = result.Skip(skip);
        //        // 以pagesize为标准显示一定量的数据
        //        result = result.Take(pageSize);

        //        // include vs join
        //        var items = await result.ToListAsync();

        //        return new PaginationList<T>(currentPage, pageSize, items);
        //    }
        //高端分页---第一部分改造PaginationList
        public int TotalPages { get; private set; }//页面总量
        public int TotalCount { get; private set; }//数据库总数据量
        public bool HasPrevious => CurrentPage > 1;//是否有上一页
        public bool HasNext => CurrentPage < TotalPages;//是否有下一页

        public int CurrentPage { get; set; }
        public int PageSize { get; set; }

        public PaginationList(int totalCount, int currentPage, int pageSize, List<T> items)
        {
            CurrentPage = currentPage;
            PageSize = pageSize;
            AddRange(items);
            TotalCount = totalCount;
            TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize);//计算得出
        }

        public static async Task<PaginationList<T>> CreateAsync(
            int currentPage, int pageSize, IQueryable<T> result)
        {
            var totalCount = await result.CountAsync();//执行数据库总量
            // pagination
            // skip
            var skip = (currentPage - 1) * pageSize;
            result = result.Skip(skip);
            // 以pagesize为标准显示一定量的数据
            result = result.Take(pageSize);

            // include vs join
            var items = await result.ToListAsync();//执行数据库列表

            return new PaginationList<T>(totalCount, currentPage, pageSize, items);
        }

    }
}
